<?php

namespace App\Models;

use Illuminate\Support\Collection;

class GoodsBase extends Model
{
    protected $table = 'yf_goods_base';
    protected $primaryKey = 'goods_id';
    public $timestamps = false;
    protected $guarded = ['goods_id'];
    protected $casts = ['goods_spec' => 'array'];

    public function goodsCommon()
    {
        return $this->hasOne(GoodsCommon::class, 'common_id', 'common_id');
    }

    public static function getGoodsListByGoodsId(array $ids) : Collection
    {
        return self::whereIn('goods_id', $ids)->get();
    }

    public function getGoodsSpecName() : string
    {
        $specName = '';
        if ($this->goods_spec) {
            $goods_spec = current($this->goods_spec);
            if (!empty($goods_spec)) {
                foreach ($goods_spec as $k => $v) {
                    $specValue = GoodsSpecValue::find($k);
                    $spec = GoodsSpec::find($specValue->spec_id);

                    $spec_base_name  = $spec->spec_name;
                    $spec_value_name = $specValue->spec_value_name;
                    $specName .= "$spec_base_name: $spec_value_name  &nbsp;";
                }
            }
        }

        return $specName;
    }

    /**
     * 商品的所有促销活动
     */
    public function getPromotions() : array
    {
        $promotions = [];
        // 团购
        if (WebConfig::value('groupbuy_allow')) {
            $promotions['groupbuy_info'] = GroupbuyBase::getNormalGroupBuyDetailByCommonId($this->common_id);
        }

        // 限时折扣，满送，加价购
        if (WebConfig::value('promotion_allow')) {
            // 限时折扣（团购优先级高，商品存在团购时，则不查询折扣）
            if (!array_get($promotions, 'groupbuy_info')) {
                $promotions['xianshi_info'] = DiscountGoods::getNormalDiscountGoodsDetailByGoodsId($this->goods_id);
            }
            // 加价购
            $promotions['increase_info'] = IncreaseBase::getIncreaseDetailByGoodsId($this->goods_id);
        }

        return $promotions;
    }
}
